package com.hpradip.android.accessNumberSpeedDialer;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public class SearchableActivity extends AccessNumberSpeedDialerActivity {

	private ProgressDialog progressDialog;
	private GoogleAnalyticsTracker tracker;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// Get the intent, verify the action and get the query
		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			searchContacts(query);
		}

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.setAnonymizeIp(true);
		tracker.startNewSession(
				getResources().getString(R.string.analytics_tracking_code),
				this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			searchContacts(query);
		}
		super.onNewIntent(intent);
	}

	private void searchContacts(final String query) {
		Runnable feedSearchable = new Runnable() {
			private List<Contact> results;

			public void run() {
				results = new ArrayList<Contact>();
				String lowerCaseQuery = query.trim().toLowerCase();
				List<Contact> contacts = new ContactsProvider()
						.loadContacts(SearchableActivity.this);
				for (Contact contact : contacts) {

					if (contact.getName().toLowerCase()
							.contains(lowerCaseQuery)
							|| contact.getNumber().toLowerCase()
									.contains(lowerCaseQuery))
						results.add(contact);
				}

				handler.sendEmptyMessage(0);
			}

			private Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {

					tracker.trackEvent("UserActions", // Category
							"Search", // Action
							"clicked", // Label
							1);

					contactsAdapter = new ContactsAdapter(
							SearchableActivity.this,
							R.layout.contacts_list_item, results);
					setListAdapter(contactsAdapter);
					progressDialog.dismiss();
				}
			};
		};

		new Thread(feedSearchable, "ContactsSearcher").start();
		progressDialog = ProgressDialog.show(this, "Please wait",
				"Searching contact", true);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		tracker.dispatch();
	}
}
